#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>

void read_childproc(int sig);
void error_handling(char * message);
void write_routine(int sock,char * buf);
void read_routine(int sock,char * buf);


#define BUF_SIZE 30



int main(int argc ,char * argv[])
{

    int clnt_sock;
    struct sockaddr_in serv_addr;

    pid_t pid;
    struct sigaction act;
    socklen_t addr_sz;
    int str_len,state;
    char buf[BUF_SIZE];

    if(argc !=3)
    {
        printf("Usage :%s  <IP> <port>\n",argv[0]);
        exit(0);
    }

    act.sa_handler = read_childproc;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    state = sigaction(SIGCHLD,&act,0);

    clnt_sock = socket(PF_INET,SOCK_STREAM,0);
    memset(&serv_addr,0,sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
    serv_addr.sin_port = htons(atoi(argv[2]));

    // if(bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) ==-1)
    //     error_handling("bing error...");
    // printf("binding....\n");

    // if(listen(serv_sock,5) == -1)
    //     error_handling("listen error...");
    // printf("listening....\n");

    if(connect(clnt_sock,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) == -1)
        error_handling("connect() error");
    
    pid = fork();
    if(pid ==0)
    {
        write_routine(clnt_sock,buf);
    }
    else
    {
        read_routine(clnt_sock,buf);
    }
    close(clnt_sock);
    return 0;
    
}
void write_routine(int sock,char * buf)
{
    while(1)
    {
        fgets(buf,BUF_SIZE,stdin);
        if( !strcmp(buf,"q\n") || !strcmp(buf,"Q\n"))
        {
            shutdown(sock,SHUT_WR);
            return ;
        }
        write(sock,buf,strlen(buf));
    }
}
void read_routine(int sock,char * buf)
{
    while(1)
    {
        int str_len = read(sock,buf,BUF_SIZE);
        if(str_len ==0)
            return ;
        buf[str_len] =0;
        printf("Message from server : %s",buf);
    }
}


void read_childproc(int sig)
{
    int status ;
    pid_t id = waitpid(-1,&status,WNOHANG);
    if(WIFEXITED(status))
    {
        printf("Removed proc id : %d\n",id);
        printf("Child send : %d \n",WIFEXITED(status));
    }
}

void error_handling(char * message)
{
    printf("%s \n",message);
    exit(1);
}
